package com.alit.face.koala.service;

import java.util.HashMap;
import java.util.Map;

import org.apache.tomcat.util.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alit.face.koala.bean.http.KoalaRequestData;
import com.alit.face.koala.co.BaiduFaceTokenCO;
import com.alit.face.koala.entity.BaiduFaceMatchEntity;
import com.alit.face.koala.entity.KoalaCemara;
import com.alit.face.koala.entity.UploadFileEntity;
import com.alit.face.koala.projectvariable.PVK;
import com.alit.face.koala.repository.BaiduFaceMatchRepository;
import com.alit.face.koala.service.face.baidu.BaiduFaceService;
import com.alit.face.koala.util.JsonUtil;
import com.alit.face.koala.vo.GreetingVO;
import com.litong.utils.projectvariable.PVU;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class KoalaStrangerSerive {
  public boolean isIdle = true;
  public Map<String, BaiduFaceTokenCO> lastFace = new HashMap<>();;
  @Autowired
  private KoalaMqService koalaMqService;
  @Autowired
  private KoalaHistoryCallbackService koalaHistoryCallbackServcie;
  @Autowired
  private BaiduFaceService baiduFaceService;
  @Autowired
  private BaiduFaceMatchRepository baiduFaceMatchRepository;

  public Map<String, BaiduFaceTokenCO> getLatFace() {
    return lastFace;
  }

  public void index(KoalaRequestData koalaRequestData, String ip, KoalaCemara koalaCemara,
      UploadFileEntity uploadFileEntity) {
    double faceSimilarity = PVU.getDouble(PVK.baiduFaceMatchSimilarity);
    String koalaStrangerSayString = PVU.getValue(PVK.koalaStrangerSayString);
    BaiduFaceTokenCO lastFaceCo = lastFace.get(koalaRequestData.getScreenToken());
    if (lastFaceCo == null) {
      lastFace = first(koalaRequestData, ip, koalaCemara, uploadFileEntity, koalaStrangerSayString);
      return;
    } else {
    }

    JSONObject matched = null;
    String encodeBase64String = Base64.encodeBase64String(uploadFileEntity.getBytes());
    // 当在请百度的时候idle的状态为false,请求完成后idle的状态是true
    isIdle = false;
    if (lastFaceCo.getFaceToken() == null) {
      log.info("启动后检测到的第2个人脸,使用base64进行比对,图1和图2," + lastFaceCo.getImgMd5() + "," + uploadFileEntity.getMd5());
      matched = baiduFaceService.match(lastFaceCo.getBase64Code(), encodeBase64String);
    } else {
      // 判断faceToken是否过期,如果过期使用base64code
      log.info("faceToken is expire {}", lastFaceCo.isExpire());
      if (lastFaceCo.isExpire()) {
        log.info("启动后检测到的第N个人脸,使用base64和base64进行比对,图1和图2," + lastFaceCo.getImgMd5() + "," + uploadFileEntity.getMd5());
        matched = baiduFaceService.match(lastFaceCo.getBase64Code(), encodeBase64String);
      } else {
        log.info(
            "启动后检测到的第N个人脸,使用face_token和base64进行比对,图1和图2," + lastFaceCo.getImgMd5() + "," + uploadFileEntity.getMd5());
        log.info("facetoken:{}", lastFaceCo.getFaceToken());
        matched = baiduFaceService.matchFaceTotenImage(lastFaceCo.getFaceToken(), encodeBase64String);
      }
    }
    isIdle = true;
    int errorCode = JsonUtil.getInt(matched, "error_code");
    if (errorCode != 0) {
      log.info("人脸比对发生错误:" + matched);
      return;
    }
    org.json.JSONObject result = JsonUtil.getJSONObject(matched, "result");
    double score = JsonUtil.getDouble(result, "score");
    log.info("比对的相似度:" + score);
    if (score < faceSimilarity) {
      koalaMqService.sendMessage(koalaCemara, GreetingVO.buildStranger(koalaStrangerSayString));
    }

    // 保存对比结果
    BaiduFaceMatchEntity entity = new BaiduFaceMatchEntity();
    entity.setScore(score);
    entity.setImgMd51(lastFaceCo.getImgMd5());
    entity.setImgMd52(uploadFileEntity.getMd5());
    baiduFaceMatchRepository.save(entity);

    // 保存第一张脸的face_token
    JSONArray faceList = JsonUtil.getJSONArray(result, "face_list");
    org.json.JSONObject face1 = JsonUtil.getJSONObject(faceList, 0);
    String faceToken1 = JsonUtil.getString(face1, "face_token");
    lastFaceCo.setFaceToken(faceToken1);

    // 保存第二张脸的face_token,并更新lastFace的中faceToken为第二张脸的faceToken
    org.json.JSONObject face2 = JsonUtil.getJSONObject(faceList, 1);
    String faceToken2 = JsonUtil.getString(face2, "face_token");

    lastFaceCo.setImgMd5(uploadFileEntity.getMd5());
    lastFaceCo.setBase64Code(encodeBase64String);
    lastFaceCo.setFaceToken(faceToken2);
    lastFaceCo.setExpireTime(System.currentTimeMillis() + 3600 * 1000);
  }

  public Map<String, BaiduFaceTokenCO> first(KoalaRequestData koalaRequestData, String ip, KoalaCemara koalaCemara,
      UploadFileEntity uploadFileEntity, String koalaStrangerSayString) {
    log.info("启动后检测到的第一个人脸,发送消息");
    koalaMqService.sendMessage(koalaCemara, GreetingVO.buildStranger(koalaStrangerSayString));
    koalaHistoryCallbackServcie.saveHistory(koalaRequestData, ip, null, null, false);
    BaiduFaceTokenCO lastFaceCo = new BaiduFaceTokenCO();
    lastFace.put(koalaRequestData.getScreenToken(), lastFaceCo);

    lastFaceCo.setImgMd5(uploadFileEntity.getMd5());
    String encodeBase64String = Base64.encodeBase64String(uploadFileEntity.getBytes());
    lastFaceCo.setBase64Code(encodeBase64String);

    return lastFace;
  }
}